package tools.project.controller {
	import ghostcat.operation.FunctionOper;
	import ghostcat.operation.Queue;

	import kiwi.debug.Log;

	import tools.model.EditorConfig;

	import com.adobe.utils.StringUtil;

	import org.aswing.JOptionPane;
	import org.robotlegs.mvcs.Command;

	import flash.filesystem.File;

	/**
	 * 批量转换用的
	 * @author zhangming.luo
	 */
	public class TransCommand extends Command {
		[Inject]
		public var config : EditorConfig;
		private var baseDir : String;

		override public function execute() : void {
			JOptionPane.showInputDialog("选择目录", "输入需要批量转换的目录", handleInput, "e:\\Desktop\\mengjiang");
		}

		private function handleInput(path : String) : void {
//			if (!StringUtil.endsWith(path, "\\asset")) {
//				JOptionPane.showMessageDialog("警告", "请提供以asset结尾的标准目录");
//				return;
//			}
			var dir : File = File.applicationDirectory.resolvePath(path);
			baseDir = dir.nativePath;
			if (!dir.exists) {
				Log.error("目录不存在");
				return;
			}
			TransOper.config = config;
			TransOper.baseDir = baseDir;
			var tmp : Array = [dir];
			var operList : Array = [];
			while (tmp.length) {
				for each (var file:File in tmp.pop().getDirectoryListing()) {
					if (file.isDirectory) {
						tmp.push(file);
						continue;
					}
					if (file.extension == "swf" && !file.parent.resolvePath(file.name.replace(file.extension, "ani")).exists) {
						operList.push(new TransOper(file));
					}
				}
			}
			operList.sort(function(a : TransOper, b : TransOper) : Number {
				return a.file.size == b.file.size ? 0 : (a.file.size > b.file.size ? 1 : -1);
			});
			operList.push(new FunctionOper(Log.alert, ["结束了"]));
			var queue : Queue = new Queue(operList);
			queue.execute();
		}
	}
}
import com.greensock.loading.SWFLoader;
import com.greensock.loading.data.SWFLoaderVars;

import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.NativeProcessExitEvent;
import flash.events.ProgressEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.clearInterval;
import flash.utils.setInterval;

import ghostcat.fileformat.png.PNGEncoder;
import ghostcat.operation.Oper;

import kiwi.debug.Log;
import kiwi.util.sprintf;

import tools.model.EditorConfig;

class TransOper extends Oper {
	public static var config : EditorConfig;
	public static var baseDir : String;
	public var file : File;
	private var loader : SWFLoader;
	private var dir : File;
	private var interval : uint;

	public function TransOper(file : File) {
		this.file = file;
		dir = file.parent/*.resolvePath(file.name.replace("." + file.extension, ""))*/;
	}

	override public function execute() : void {
		super.execute();
		loader = new SWFLoader(file.nativePath, new SWFLoaderVars().onComplete(handleComplete));
		loader.load();
	}

	private function handleComplete(item : *) : void {
		dir.createDirectory();
		var textureClz : Class = loader.getClass("TEXTURE");
		var textureConfClz : Class = loader.getClass("TEXTURE_CONF");
		var source : * = new textureClz;
		var bd : BitmapData = source is Bitmap ? source.bitmapData : source;
		var xml : XML = new XML(new textureConfClz());
		saveBitmap(bd, dir.resolvePath("./"+file.name.replace(file.type,"")+".png"));
		saveXML(xml, dir.resolvePath("./"+file.name.replace(file.type,"")+".xml"));
		Log.info("导出完毕 " + dir.nativePath);
		loader.unload();
		packageWithFlash();
	}

	private function saveXML(xml : XML, path : File) : void {
		var out : FileStream = new FileStream();
		out.open(path, FileMode.WRITE);
		out.writeUTFBytes(xml.toXMLString());
		out.close();
	}

	private function saveBitmap(bd : BitmapData, path : File) : void {
		var out : FileStream = new FileStream();
		out.open(path, FileMode.WRITE);
		out.writeBytes(PNGEncoder.encode(bd));
		out.close();
	}

	protected function packageWithFlash() : void {
		var prefix : String = file.nativePath.replace(baseDir, "").replace("." + file.extension, "").replace(/\\/g, "_");
		var jsfl : String = <![CDATA[
				//pkg(fl.browseForFolderURL("请选择素材文件夹"),80);
				function pkg(folderPath,spriteName,quality){
					var spriteName;
					// 清理输出
					fl.outputPanel.clear();
					// 创建新文件
					fl.createDocument();
					var dom = fl.getDocumentDOM();
					var lib = fl.getDocumentDOM().library;
					// 导入类
				 	FLfile.write(folderPath+"/ENTRY.as","package{import flash.display.*;public class ENTRY extends MovieClip{TEXTURE_CONF${prefix};TEXTURE${prefix};}}");
				 	dom.docClass="ENTRY";
					fl.trace("主脚本生成成功");
					FLfile.write(folderPath+"/TEXTURE_CONF${prefix}.as","package{import flash.utils.*;[Embed(source=\""+spriteName+".xml\",mimeType=\"application/octet-stream\")]public class TEXTURE_CONF${prefix} extends ByteArray {}}");
					fl.trace("导出配置文件成功");
					// 打开文件夹
					fl.trace("我擦擦："+folderPath + "/"+spriteName+".png");
					dom.importFile(folderPath + "/"+spriteName+".png");
					fl.trace("导入图片成功");
				 	lib.selectItem(spriteName+".png");
				 	// 清场
					dom.selectAll(); 
					dom.deleteSelection();
				 	// 导出位图链接
				 	lib.setItemProperty("allowSmoothing",false);
				 	lib.setItemProperty("linkageExportForAS",true);
				 	lib.setItemProperty("linkageExportInFirstFrame",true);
				 	lib.setItemProperty("linkageBaseClass","flash.display.BitmapData");
				 	lib.setItemProperty("linkageClassName","TEXTURE${prefix}");
				 	lib.setItemProperty("compressionType","photo");
					lib.setItemProperty("quality",quality);
					fl.trace("导出图片成功");
					
					// 保存配置类
					fl.saveDocument(dom,folderPath+"/"+spriteName+".fla");
					dom.swfJPEGQuality=quality;
					dom.exportSWF(folderPath+"/"+spriteName+".swf",true);
					dom.close();
					FLfile.copy(folderPath+"/"+spriteName+".swf",folderPath+"/../"+spriteName+".ani");
					FLfile.remove(folderPath+"/ENTRY.as");
					FLfile.remove(folderPath+"/TEXTURE_CONF${prefix}.as");
					FLfile.remove(folderPath+"/"+spriteName+".fla");
					FLfile.remove(folderPath+"/"+spriteName+".jsfl");
					FLfile.remove(folderPath+"/"+spriteName+".swf");
					FLfile.remove(folderPath+"/"+spriteName+".png");
					FLfile.remove(folderPath+"/"+spriteName+".xml");

					//FLfile.remove(folderPath);
				}
			]]>;
		if (config.flash == null) {
			Log.alert("Flash没有找到");
			fault();
			return;
		}
		var flash : File = File.applicationDirectory.resolvePath(config.flash);
		if (!flash.exists) {
			Log.alert("Flash.exe没有找到");
			fault();
			return;
		}
		var out : FileStream = new FileStream();
		var jsflFile : File = dir.resolvePath(file.name.replace("." + file.extension, "")+".jsfl");
		out.open(jsflFile, FileMode.WRITE);
		out.writeByte(0xEF);
		out.writeByte(0xBB);
		out.writeByte(0xBF);
		out.writeUTFBytes(jsfl.replace(/\$\{prefix\}/g, prefix));
		out.writeUTFBytes(sprintf("pkg(\"file:///%s\",\"%s\",%d);", dir.nativePath.replace(/\\/g, "/"), file.name.replace("." + file.extension, ""), 80));
		out.close();
		run(flash, [jsflFile.nativePath], function() : void {
			interval = setInterval(check, 1000);
		}, Log.info, Log.alert);
	}

	private function check() : void {
		if (!dir.resolvePath(file.name.replace("." + file.extension, "")+".jsfl").exists) {
			clearInterval(interval);
			Log.info("转换完毕 " + file.nativePath);
			result();
		}
	}

	private function run(file : File, arg : Array = null, exitHandler : Function = null, traceHandler : Function = null, errorHandler : Function = null, workingDirectory : File = null) : void {
		var nativeProcessStartupInfo : NativeProcessStartupInfo = new NativeProcessStartupInfo();
		nativeProcessStartupInfo.executable = file;
		nativeProcessStartupInfo.workingDirectory = workingDirectory;
		if (arg) {
			var vector : Vector.<String> = new Vector.<String>();
			vector.push.apply(null, arg);
			nativeProcessStartupInfo.arguments = vector;
		}
		var process : NativeProcess = new NativeProcess();
		if (dataHandler != null) {
			process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, dataHandler);
			process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, dataHandler);
		}
		if (exitHandler != null) {
			process.addEventListener(NativeProcessExitEvent.EXIT, exitHandler);
		}
		try
		{
			process.start(nativeProcessStartupInfo);
		} 
		catch(error:Error) 
		{
			Log.alert("批量转转出错,好像可以忽略");
		}
		return;
		function dataHandler(event : Event) : void {
			var process : NativeProcess = event.currentTarget as NativeProcess;
			var str : String;
			if (event.type == ProgressEvent.STANDARD_OUTPUT_DATA) {
				str = process.standardOutput.readMultiByte(process.standardOutput.bytesAvailable, "gb2312").toString();
				if (traceHandler != null) {
					traceHandler(str);
				}
			} else {
				str = process.standardError.readMultiByte(process.standardError.bytesAvailable, "gb2312").toString();
				if (errorHandler != null) {
					errorHandler(str);
				}
			}
		}
	}
}